package com.atguigu.gulimall.product.service.impl;

import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        List<CategoryEntity> list = this.getBaseMapper().selectList(null);
        List<CategoryEntity> firstLevelList = list.stream().filter(e -> e.getCatLevel() == 1).collect(Collectors.toList());
        List<CategoryEntity> secondLevelList = list.stream().filter(e -> e.getCatLevel() == 2).collect(Collectors.toList());
        List<CategoryEntity> thirdLevelList = list.stream().filter(e -> e.getCatLevel() == 3).collect(Collectors.toList());
        for (CategoryEntity ce : firstLevelList) {
            Long catId = ce.getCatId();
            List<CategoryEntity> secondSubList = secondLevelList.stream().filter(e -> e.getParentCid() == catId).collect(Collectors.toList());
            ce.setChildren(secondSubList);
            for (CategoryEntity ce2 : secondSubList) {
                Long catId2 = ce2.getCatId();
                List<CategoryEntity> thirdSubList = thirdLevelList.stream().filter(e -> e.getParentCid() == catId2).collect(Collectors.toList());
                ce2.setChildren(thirdSubList);
            }
        }
        return firstLevelList;
    }

}